<template>
  <div style="width: 100%;height: 100%;">
    <BaseMainSlot :show-tab="true">
      <template v-slot:search-box>
        <SearchForm :form-config="formConfig" :form-data="filterData" @search="search" />
      </template>
      <template v-slot:btn-box>
        <div class="page-top__todo">
          <CommonBtn @click="reload">刷新</CommonBtn>
          <CommonBtn @click="addEditShow = true">添加</CommonBtn>
          <CommonBtn :disabled="!delActive" @click="del">删除</CommonBtn>
        </div>
      </template>
      <template v-slot:content>
        <div class="content-wrapper">
          <el-table v-loading="tableLoading" :data="tableData" stripe border height="calc(100% - 50px)" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" :selectable="$utils.selectable" width="55" />
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column prop="materialTypeName" label="物料类型">
              <template v-if="!('index' in scope.row)" slot-scope="scope">
                {{ scope.row.material && scope.row.material.materialTypeName }}
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" />
            <el-table-column prop="materialspec" label="型号参数">
              <template v-if="!('index' in scope.row)" slot-scope="scope">
                {{ scope.row.material && scope.row.material.materialspec }}
              </template>
            </el-table-column>
            <el-table-column prop="model" label="规格参数">
              <template v-if="!('index' in scope.row)" slot-scope="scope">
                {{ scope.row.material && scope.row.material.model }}
              </template>
            </el-table-column>
            <el-table-column prop="processesList" label="包含工序">
              <template v-if="!('index' in scope.row)" slot-scope="scope">
                <span v-for="(item, index) in scope.row.processesList" :key="index">
                  {{ item.processesName }}
                  <i v-if="index !== scope.row.processesList.length - 1">-</i>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="工艺工序配置状态">
              <template v-if="!('index' in scope.row)" slot-scope="scope">
                <span :class="'status-' + (scope.row.status ? '1' : '0')">{{ scope.row.status ? (scope.row.status === true ? '已配置' : '未配置') : '未配置' }}</span>
              </template>
            </el-table-column>
            <el-table-column width="250" label="操作">
              <template v-if="!('index' in scope.row)" slot-scope="scope">
                <el-button type="text" class="text-btn-cursor" size="small" @click="edit(scope.row)">修改</el-button>
                <el-button type="text" class="text-btn-cursor" size="small" @click="editWorkmanship(scope.row)">工艺工序</el-button>
                <el-button type="text" class="text-btn-cursor" size="small" @click="editBom(scope.row)">物料清单</el-button>
                <el-button type="text" class="text-btn-cursor cursor-delete" size="small" @click="handleDelete(scope.row.productId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
        </div>
      </template>
    </BaseMainSlot>
    <AddEditDialog v-model="addEditShow" :selected-item="selectedItem" :prod-list="finishProductList" @reflash="search" />
    <WorkmanshipDialog v-model="workmanshipShow" :selected-item="selectedItem" @reflash="search" @updateSelectedItem="updateSelectedItem" />
    <BomDialog v-model="bomShow" :selected-item="selectedItem" :material-list="materialList" @reflash="search" />
  </div>
</template>
<script>
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot';
import SearchForm from '@/components/searchForm';
import Pagination from '@/components/Pagination';
import nowpagereq from '@/api/processing-management/basic-info-manage/agr-source-base-Manage';
import api from '@/api/processing-management/basic-info-manage/product-process';
import AddEditDialog from './components/add-edit-dialog.vue';
import WorkmanshipDialog from './components/workmanship-dialog.vue';
import BomDialog from './components/bom-dialog.vue';
export default {
  inject: ['reload'],
  components: {
    BaseMainSlot,
    SearchForm,
    Pagination,
    AddEditDialog,
    WorkmanshipDialog,
    BomDialog
  },
  props: {},
  data() {
    return {
      tableData: [],
      tableLoading: false,
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      formConfig: [
        {
          label: '物料类型',
          prop: 'materialTypeNo',
          type: 'cascader',
          options: [],
          optionKey: {
            expandTrigger: 'hover',
            value: 'materialTypeNo',
            label: 'materialTypeName',
            children: 'child',
            multiple: false,
            checkStrictly: true
          }
        },
        {
          label: '产品名称',
          prop: 'productName',
          type: 'input'
        }
      ],
      filterData: {},
      addEditShow: false,
      finishProductList: [],
      selectedList: [],
      delActive: false,
      selectedItem: null,
      workmanshipShow: false,
      bomShow: false,
      materialList: []
    };
  },
  watch: {
    addEditShow(v) {
      if (!v) {
        this.selectedItem = null;
      }
    },
    workmanshipShow(v) {
      if (!v) {
        this.selectedItem = null;
      }
    },
    bomShow(v) {
      if (!v) {
        this.selectedItem = null;
      }
    }
  },
  created() {
    this.getSelect();
    this.getFinishProductList();
    this.getMaterial();
    this.search();
  },
  mounted() {
    // this.handleDelete(46);
  },
  methods: {
    handleSelectionChange(list) {
      this.selectedList = list.map(item => {
        return item.productId;
      });
      if (this.selectedList && this.selectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.search();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.search();
    },
    search() {
      const { currentPage, pageSize } = this;
      const filterData = JSON.parse(JSON.stringify(this.filterData));
      if (Object.prototype.hasOwnProperty.call(filterData, 'materialTypeNo')) {
        filterData.materialTypeNo = filterData.materialTypeNo[0];
      }
      this.tableLoading = true;
      api
        .queryPageByCondition({
          page: currentPage,
          size: pageSize,
          entity: {
            ...filterData
          }
        })
        .then(res => {
          if (res.code === 1) {
            this.tableData = this.$utils.addblankmet(res.data.content, pageSize);
            this.totalSize = res.data.totalElements;
            if (res.data.content.length === 0 && this.currentPage !== 1) {
              this.currentPage--;
              this.search();
            }
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    async getSelect() {
      let result = await nowpagereq.getFarmingAssetLists();
      this.formConfig.find(i => i.prop === 'materialTypeNo').options = result.data;
    },
    getFinishProductList() {
      const params = {
        finishProductType: true
      };
      nowpagereq.getMaterial(params).then(res => {
        this.finishProductList = res.data;
      });
    },
    getMaterial() {
      const params = {
        rawType: true
      };
      nowpagereq.getMaterial(params).then(res => {
        this.materialList = res.data;
      });
    },
    edit(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.addEditShow = true;
    },
    editWorkmanship(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.workmanshipShow = true;
    },
    editBom(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.bomShow = true;
    },
    del() {
      this.handleDelete(this.selectedList);
    },
    handleDelete(no) {
      let list = [no];
      if (no instanceof Array) {
        list = no;
      }
      this.$confirm('是否确认删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          api.delProduct({ productIdList: list }).then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功');
              this.search();
            } else {
              this.$message.error('删除失败');
            }
          });
        })
        .catch(action => {});
    },
    updateSelectedItem(item) {
      this.selectedItem = item;
    }
  }
};
</script>
<style lang="scss" scoped>
.content-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
}
.status-1 {
  color: #67c23a;
}
</style>
